# -*- coding: UTF-8 -*-

from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page

# Create your views here.

from .forms import MenuForm, MyUserMenu_Form

from .forms import Menu_Search_Form
from public.function import Public
from django.contrib.auth.models import User 
from menu.models import  MyUserMenu,Menu 
from django.shortcuts import  get_object_or_404
from django.http import JsonResponse
from .function import Menu_Mananger

@login_required()
def menu_list(request):
    cls = Public()
    return cls.url_get(request, app="menu", template="menu_list",
                form=MenuForm, models=Menu,
                 search_form=Menu_Search_Form)


@login_required()
def menu_mananger(request):
    cls =Menu_Mananger()
    return cls.url_get(request, app="menu", template="menu_mananger",form=MyUserMenu_Form, models=MyUserMenu,search_form=Menu_Search_Form)




#用户菜单
@cache_page(60 * 15)
@login_required()
def user_menu(request):
    user = request.user or None
    userid = User.objects.get(username=user).id
    rows = Menu.objects.filter(parent_id=0)
    user_url_list = MyUserMenu.objects.get(user_id=userid).menus_show
    user_url_list = user_url_list.split(",")
    urlrows = Menu.objects.filter(id__in=user_url_list)
    templist=[]

    for var in rows:
        tempdict={}
        t_list = []
        for uservar in urlrows:

            if var.id == uservar.parent_id:
                t_list.append({"name":uservar.text,"url_name":"/".join((uservar.namespace,uservar.url_name))})
        if len(t_list)>0:
            tempdict['name'] = var.text
            tempdict['list']=t_list
        if tempdict:
            templist.append(tempdict)
        del tempdict, t_list
    return JsonResponse(templist,safe=False)



